package org.blog.servlets;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.blog.beans.Blog;
import org.blog.beans.User;
import org.blog.controller.UserController;
import org.blog.exceptions.BlogException;
import org.blog.exceptions.InvalidMailException;
import org.blog.exceptions.SettingsException;
import org.blog.logic.BlogLogic;
import org.blog.logic.UserLogic;
import org.blog.messages.BlogMessage;
import org.blog.messages.UserSettingsMessage;

/**
 * Servlet implementation class UserSettings
 */
public class AddBlog extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
 
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		action(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		action(request, response);
	}
	
	private void action(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		
		if("add".equals(request.getParameter("do"))) {
			
			Blog blog = new Blog();
			try {
				BeanUtils.populate(blog, request.getParameterMap());
				blog.setUserId(UserController.getUser(request.getSession()).getId());
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
			
			BlogMessage bm = new BlogMessage();
			
			try {
				BlogLogic.getInstance().add(blog);
			} catch (BlogException e) {

				switch(e.getType()) {
				
				case 1:
					bm.setName("niepoprawna nazwa");
					break;
				case 2:
					bm.setDescription("niepoprawny opis");
					break;
				}
			}
			if(bm.error) {
				request.setAttribute("message", bm);
				request.setAttribute("blog", blog);
				getServletContext().getRequestDispatcher("/WEB-INF/jsp/addBlog.jsp").forward(request, response);
			}
			else {
				request.setAttribute("message", "Operacja zakonczona powodzeniem");
				getServletContext().getRequestDispatcher("/WEB-INF/jsp/success.jsp").forward(request, response);
			}
			
			
			
		}
		else
			getServletContext().getRequestDispatcher("/WEB-INF/jsp/addBlog.jsp").forward(request, response);
		
	}

}
